{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "928a94f9-58e0-41d8-a406-b4cda4ef7502",
   "metadata": {},
   "outputs": [],
   "source": [
    "丢弃法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1bd5ea07-dd08-4ac7-a896-38ee376a31fd",
   "metadata": {},
   "outputs": [],
   "source": [
    "除了权重衰减外还可以用丢弃法应对过拟合问题\n",
    "当对隐藏层使用丢弃法时，该层的隐藏单元会有一定概率被丢弃，丢弃的概率时超参数\n",
    "丢弃发不改变其输入的期望值，可以使得输出值不依赖隐藏单元，从而解决过拟合的问题\n",
    "但是在测试模型时，为了得到正确的结果，一般不使用丢弃法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "16ef6bd3-9589-4bb7-9181-4c4145b8e960",
   "metadata": {},
   "outputs": [],
   "source": [
    "#从零开始实现\n",
    "%matplotlib inline\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "import numpy as np\n",
    "import sys\n",
    "sys.path.append(\"..\") \n",
    "import d2lzh_pytorch as d2l\n",
    "def dropout(X, drop_prob):\n",
    "    X = X.float()\n",
    "    assert 0 <= drop_prob <= 1\n",
    "    keep_prob = 1 - drop_prob\n",
    "    # 这种情况下把全部元素都丢弃\n",
    "    if keep_prob == 0:\n",
    "        return torch.zeros_like(X)\n",
    "    mask = (torch.randn(X.shape) < keep_prob).float()\n",
    "    #这一部分为了保证输出的结果总值是一致的，所以需要除以概率\n",
    "    return mask * X / keep_prob"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "33e10c70-5faa-4a48-8c1c-4fe558af12ea",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[ 0.,  1.,  2.,  3.,  4.,  5.,  0.,  7.],\n",
       "        [ 8.,  9., 10., 11., 12., 13., 14., 15.]])"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X = torch.arange(16).view(2, 8)\n",
    "dropout(X, 0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "aac84161-0dab-4b83-a94e-8ec013fffc43",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[ 0.,  2.,  4.,  6.,  8.,  0., 12., 14.],\n",
       "        [16., 18., 20., 22.,  0., 26., 28.,  0.]])"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dropout(X, 0.5)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "172723c3-1778-41ab-a281-cbec7701e6be",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[0., 0., 0., 0., 0., 0., 0., 0.],\n",
       "        [0., 0., 0., 0., 0., 0., 0., 0.]])"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dropout(X, 1.0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "67428379-aaa6-4da6-a498-dca0e13b3725",
   "metadata": {},
   "outputs": [],
   "source": [
    "#定义模型参数\n",
    "num_inputs, num_outputs, num_hiddens1, num_hiddens2 = 784, 10, 256, 256\n",
    "W1 = torch.tensor(np.random.normal(0, 0.01, size=(num_inputs, num_hiddens1)), dtype=torch.float, requires_grad=True)\n",
    "b1 = torch.zeros(num_hiddens1, requires_grad=True)\n",
    "W2 = torch.tensor(np.random.normal(0, 0.01, size=(num_hiddens1, num_hiddens2)), dtype=torch.float, requires_grad=True)\n",
    "b2 = torch.zeros(num_hiddens2, requires_grad=True)\n",
    "W3 = torch.tensor(np.random.normal(0, 0.01, size=(num_hiddens2, num_outputs)), dtype=torch.float, requires_grad=True)\n",
    "b3 = torch.zeros(num_outputs, requires_grad=True)\n",
    "params = [W1, b1, W2, b2, W3, b3]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "fee9f5a3-f881-4da3-95b2-529633b5e1b3",
   "metadata": {},
   "outputs": [],
   "source": [
    "#定义模型\n",
    "drop_prob1, drop_prob2 = 0.2, 0.5\n",
    "def net(X, is_training=True):\n",
    "    X = X.view(-1, num_inputs)\n",
    "    H1 = (torch.matmul(X, W1) + b1).relu()\n",
    "    if is_training: # 只在训练模型时使⽤丢弃法\n",
    "        H1 = dropout(H1, drop_prob1) # 在第⼀层全连接后添加丢弃层\n",
    "        H2 = (torch.matmul(H1, W2) + b2).relu()\n",
    "    if is_training:\n",
    "        H2 = dropout(H2, drop_prob2) # 在第⼆层全连接后添加丢弃层\n",
    "    return torch.matmul(H2, W3) + b3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "2fecfef6-b8e8-441f-9ee3-70d7bdcd0d33",
   "metadata": {},
   "outputs": [],
   "source": [
    "#模型评估\n",
    "# 本函数已保存在d2lzh_pytorch\n",
    "def evaluate_accuracy(data_iter, net):\n",
    "    acc_sum, n = 0.0, 0\n",
    "    for X, y in data_iter:\n",
    "        if isinstance(net, torch.nn.Module):\n",
    "            net.eval() # 评估模式, 这会关闭dropout\n",
    "            acc_sum += (net(X).argmax(dim=1) == y).float().sum().item()\n",
    "            net.train() # 改回训练模式\n",
    "        else: # ⾃定义的模型\n",
    "            if('is_training' in net.__code__.co_varnames): # 如果有is_training这个参数\n",
    "                # 将is_training设置成False\n",
    "                acc_sum += (net(X, is_training=False).argmax(dim=1) == y).float().sum().item() \n",
    "            else:\n",
    "                acc_sum += (net(X).argmax(dim=1) == y).float().sum().item() \n",
    "        n += y.shape[0]\n",
    "    return acc_sum / n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "23e270dc-7040-4aae-9343-ca69bc9060fa",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, loss 0.0040, train acc 0.616, test acc 0.747\n",
      "epoch 2, loss 0.0021, train acc 0.805, test acc 0.821\n",
      "epoch 3, loss 0.0019, train acc 0.829, test acc 0.833\n",
      "epoch 4, loss 0.0017, train acc 0.844, test acc 0.835\n",
      "epoch 5, loss 0.0015, train acc 0.856, test acc 0.839\n"
     ]
    }
   ],
   "source": [
    "#训练与测试模型\n",
    "num_epochs, lr, batch_size = 5, 100.0, 256\n",
    "loss = torch.nn.CrossEntropyLoss()\n",
    "train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)\n",
    "d2l.train_softmax(net, train_iter, test_iter, loss, num_epochs, batch_size, params, lr)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0634e795-853a-4e04-a123-1a51719983e7",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python [conda env:pytorch]",
   "language": "python",
   "name": "deep_learning"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.15"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
